package com.qing.springcloud.handler;

import com.qing.springcloud.manger.UserChannelManager;
import com.qing.springcloud.model.ChatMessage;
import com.qing.springcloud.model.MsgType;
import com.qing.springcloud.service.ChatGroupService;
import com.qing.springcloud.service.MessageService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * @author caozhipeng
 * @date 2025/7/9
 */
@ChannelHandler.Sharable
@RequiredArgsConstructor
public class ChatServerHandler extends SimpleChannelInboundHandler<ChatMessage> {
    private final UserChannelManager channelManager;
    private final MessageService messageService;
    private final ChatGroupService groupService;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatMessage msg) {
        // 处理消息路由
        switch (msg.getChatType()) {
            case 0:
                handlePrivateMessage(ctx, msg);
                break;
            case 1:
                handleGroupMessage(ctx, msg);
                break;
        }
    }

    private void handlePrivateMessage(ChannelHandlerContext ctx, ChatMessage msg) {
        Channel targetChannel = channelManager.getChannel(msg.getReceiverId());

        if (targetChannel != null && targetChannel.isActive()) {
            // 用户在线，直接转发
            targetChannel.writeAndFlush(msg);

            // 发送ACK确认
            sendAck(ctx, msg.getMsgId());
        } else {
            // 用户离线，存储到数据库
            messageService.storeOfflineMessage(msg);
        }
    }

    private void handleGroupMessage(ChannelHandlerContext ctx, ChatMessage msg) {
        // 根据群ID获取所有成员
        List<Long> memberIds = groupService.getGroupMemberIds(msg.getReceiverId());

        for (Long memberId : memberIds) {
            Channel memberChannel = channelManager.getChannel(memberId);
            if (memberChannel != null && memberChannel.isActive() && !memberId.equals(msg.getSenderId())) {
                memberChannel.writeAndFlush(msg);
            }
        }

        // 发送ACK确认
        sendAck(ctx, msg.getMsgId());
    }

    private void sendAck(ChannelHandlerContext ctx, String msgId) {
        ChatMessage ackMsg = ChatMessage.builder().msgId(msgId).msgType(MsgType.ACK).build();
        ctx.writeAndFlush(ackMsg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // 用户连接时发送离线消息
        Long userId = channelManager.getUserId(ctx.channel());
        List<ChatMessage> offlineMsgs = messageService.getOfflineMessages(userId);

        for (ChatMessage msg : offlineMsgs) {
            ctx.channel().writeAndFlush(msg);
        }
    }
}